<template>
  <div id="role">
    <roledog
    :title="title"
    :action="action"
    ></roledog>
    <el-button type="primary" style="margin:10px" @click="addrole">添加角色</el-button>
    <el-table
      :data="roleData"
      style="width: 100%"
      row-key="roleid"
      border
      default-expand-all
    >
      <el-table-column prop="roleid" header-align="center" label="角色id" />
      <el-table-column prop="roleName" align="center" label="角色名称" />
      <el-table-column prop="desc" align="center" label="角色描述" />
      <el-table-column prop="status" align="center" label="角色状态" />
      <el-table-column align="center">
       
      <template #default="{row}">
       <div>
        <el-switch
      v-access="row.roleid"
      v-model="row.status"
      class="ml-2"
      inline-prompt
      style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
      active-text="启用"
      inactive-text="禁用"
      active-value="1"
      inactive-value="0"
      @change="changeStatus(row)"
    />
       </div>
      </template>
      </el-table-column>
      <el-table-column align="center">
            <template #default="{row}">
                <el-button type="primary" v-access="row.roleid" align="center" @click="handlePermissions(row)">分配权限</el-button>
                <el-button>分配角色</el-button>
            </template>
      </el-table-column>
    </el-table>
    <drawer
    v-model="flag"
     :openedFn="getgetTreePermission"
    >
    <template #tree>
  <el-tree
    ref="RefTree"
    :data="treeData"
    show-checkbox
    node-key="id"
    default-expand-all
    highlight-current
    check-on-click-node
    check-strictly
    :props="treeProps"
  />
  <el-button type="primary" @click="save">保存</el-button>
    </template>
    
    </drawer>
  </div>
</template>
<script setup>
import { ref,onMounted } from 'vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import * as permission from '@/api/permission'
import roledog from '@/components/roledog/index.vue'
import drawer from '@/components/Drawer/index.vue'
import usepermission from '@/store/permission.js'
import useStore from '@/store/user.js'
import isChild from '../../../../utils/isChild.js'
import useRole from '@/store/role.js'
import usedialog from '@/store/dialog.js'
let dialog = usedialog()
let role = useRole()
let user = useStore()
let permissionId = usepermission()
const roleData=ref([])
let flag=ref(false)
let current= ref(null)
let handlePermissions=(row)=>{
    flag.value=true
    // console.log(row);
    current.value=row.roleid
}
let getRoleData = async () =>{
    try {
        let res = await permission.getRoleListApi()
        // console.log(res);
        roleData.value=res.data.data
    } catch (error) {
        console.log(error);
    }
}
onMounted(()=>{
    getRoleData()
})
//权限设置是否禁用
let changeStatus =async (row)=>{
 try {
     // console.log(row);
     let res = await permission.updateRoleApi({roleid:row.roleid,parentid:row.parentid,status:row.status})
    // console.log(res);
    if(res.data.code === 200){
        ElMessage.success(res.data.msg)
    }
 } catch (error) {
  console.log(error);
   ElMessage.error('修改失败')
  
 }
}
const treeProps = {
  children: 'children',
  label: 'desc',
}
const treeData = ref([])
let RefTree = ref(null)
let getgetTreePermission =async ()=>{
    try {
        let res = await Promise.all([permission.getPermissionListApi(),permission.getCurrentRolePermissionListApi({ type: '1', roleid: current.value })])
        // console.log(res);
        let allPermission = res[0].data.permissionPaths
        let currentPermission = res[1].data.data
        treeData.value=allPermission

        let checkedId = currentPermission.map(item=>item.id)
        // console.log(checkedId);
        // console.log(RefTree.value);
      RefTree.value.setCheckedKeys(checkedId)
       
      //将数据扁平化
        // console.log(allPermission);
     let flatTree = (data=[])=>{
      let flatTreeArr = []
         let recursion = (arr=[]) =>{
              arr.forEach(item=>{
                let obj ={
                "_id": item._id,
                "id": item.id,
                "path": item.path,
                "desc": item.desc,
                "method": item.method,
                "parentid": item.parentid,
                "permissions": item.permissions,
                  }
                if(item.children && item.children.length>0){
                    recursion(item.children)
                }
                flatTreeArr.push(obj)
              })
         }
         recursion(data)
          return flatTreeArr
     }
     let flatAllpermission = flatTree(allPermission)
    //  console.log(flatAllpermission);
      //  console.log(user.$state.userInfo.value.roleid);
      let currentpermissionId = permissionId.currentpermissionId
      // console.log(currentpermissionId);
    if(user.$state.userInfo.value.roleid !== 1){
      flatAllpermission.forEach(item=>{
        if(!currentpermissionId.includes(item.id)){
          item.disabled=true
        }
      })
    }

    let flattoTree = (data=[])=>{
      let tree = []
      data.forEach(item=>{
        if(!item.parentid){
          tree.push(item)
        }else{
          let parent = data.find(v=>v.id===item.parentid)
          if(parent){
            if(!parent.children){
              parent.children=[]
            }
            parent.children.push(item)
          }
        }
      })
      return tree
    }
    let treeAllpermission = flattoTree(flatAllpermission)

    treeData.value=treeAllpermission



    } catch (error) {
        console.log(error);
    }
}
//自定义指令控制权限按钮禁用
let vAccess = {
  mounted(el, binding){
    let currentRoleid = user.$state.userInfo.value.roleid
    // console.log(binding.value);
    let targetRoleid = binding.value
    let allRoleid = role.allRole
    // console.log(allRoleid);
   let isChildRole = isChild(currentRoleid,targetRoleid,allRoleid)
  //  console.log(isParentRole)
    let className = el.className
    if(!isChildRole){
      el.className = className + ' is-disabled'
      el.disabled=true
      // el.removeEventListener('click',changeStatus )
      el.classList.add('point-event')
      el.parentNode.classList.add('notallowed')
    
    }
  }
}

let save = ()=>{
   let permission_ids = RefTree.value.getCheckedKeys()
   ElMessageBox.confirm('确定提交吗？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
   }).then(async ()=>{
      try {
        let res = await permission.grantRoleApi({ roleids: [current.value], permission_ids })
        console.log(res);
        if(res.data.code===200){
            flag.value=false
            ElMessage.success('授权成功')
        }
      } catch (error) {
        console.log(error);
      }
   }).catch(()=>{
       ElMessage.info('已取消授权')
   })
}
//增删改
let action = ref('add')
let title = ref('添加角色')
//添加角色
let addrole = ()=>{
  // console.log(11);
  console.log(dialog.rolevisible);
  dialog.rolevisible=true
}
</script>
<style>
.point-event{
  pointer-events: none;
}
.notallowed{
  cursor: not-allowed;
}
</style>